/// 辅助 * 请求

import { Message, RequestGenerator, formatResponse, withToken } from '@expresso/plus'
import { message } from 'ant-design-vue'
import type { InternalAxiosRequestConfig } from 'axios'
import { cache } from './cache'
import router from '@/router'
import { apiLogout, apiRefreshToken } from '@/apis/Login'

//# 定义

const requester = new Requester({
  timeout: 1000 * 60 * 2,

  reqInterceptors: [
    {
      onFulfilled(config) {
        if ([
          '/hdpu-auth/user/delivery/login',
          '/hdpu-auth/token/refreshToken',
        ].includes(config.url ?? '')) {
          return config
        }
        else {
          withToken(cache.getToken()?.accessToken, config.headers, router)
          return config
        }
      },
    },
  ],
  resInterceptors: [
    {
      onFulfilled(response) {
        switch (response.status) {
          case 200: {
            return formatResponse(response)
          }
          default:
            return response
        }
      },
      onRejected(error) {
        const { response } = error
        const result = response?.data

        //* 错误提示 *//
        Message.requestError(error, import.meta.env.PROD, () => {
          return result?.code !== '0x2010'
        })

        //* Token 过期 *//
        if (result?.code === '0x2000') {
          refreshToken(response?.config)
        }
        //* 0x2010 账号权限改变 */
        else if (result?.code === '0x2010') {
          switch (response?.status) {
            case 403: {
              logout(result)
              break
            }
          }
        }
        //* 0x2006 令牌标识不能为空 */
        else if (result?.code === '0x2006') {
          setTimeout(() => {

          })
        }
        return Promise.reject(error)
      },
    },
  ],
})

async function refreshToken(config?: InternalAxiosRequestConfig) {
  const refreshToken = cache.getToken()?.refreshToken
  if (refreshToken) {
    const res = await apiRefreshToken(refreshToken)
    if (isSucceed(res, false, false)) {
      const { accessToken, refreshToken } = res.data
      cache.setToken({ accessToken, refreshToken })
      // config && await requester.request(config)
    }
    else {
      cache.clear()
      router.push('/login')
    }
  }
}

async function logout(result: ResponseResult<any> | undefined) {
  await apiLogout()
  if (result?.message) {
    message.error(result.message, 5, () => {
      router.push('/login')
    })
  }
  else {
    router.push('/login')
  }
}

const request = RequestGenerator.request(requester)
const isSucceed = RequestGenerator.isSucceed('0x0000')

//# 导出

export { request, isSucceed }
